package geektime.spring.springbucks;

import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.model.CoffeeOrder;
import geektime.spring.springbucks.model.OrderState;
import geektime.spring.springbucks.service.CoffeeOrderService;
import geektime.spring.springbucks.service.CoffeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@EnableTransactionManagement
@SpringBootApplication
@EnableCaching(proxyTargetClass = true)
@MapperScan("geektime.spring.springbucks.mapper")
public class SpringBucksApplication implements ApplicationRunner {

	@Autowired
	private CoffeeService coffeeService;
	@Autowired
	private CoffeeOrderService orderService;

	public static void main(String[] args) {
		SpringApplication.run(SpringBucksApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {

		List<Coffee> coffees = coffeeService.findAll();
		coffees.forEach(x -> log.info("find Coffes all: {}", x));

		//查询
		Coffee latte = coffeeService.findOneCoffee("latte");
		Coffee capuccino = coffeeService.findOneCoffee("capuccino");

		//创建订单
		CoffeeOrder order = orderService.createOrder("Li Lei", latte, capuccino);

		//支付完成
		log.info("Update INIT to PAID: {}", orderService.updateState(order, OrderState.PAID));

		// 订单完成
		log.info("Update PAID to TAKEN: {}", orderService.updateState(order, OrderState.TAKEN));

		// 查询订单
		CoffeeOrder all = orderService.findById(order.getId());

		// 查询所有订单
		List<CoffeeOrder> coffeeOrders = orderService.findAll();

		// 分页查询
		coffeeService.findAllWithRowBounds(new RowBounds(1, 3))
				.forEach(c -> log.info("Page(1) Coffee {}", c));
		coffeeService.findAllWithRowBounds(new RowBounds(2, 3))
				.forEach(c -> log.info("Page(2) Coffee {}", c));

		//清楚缓存
		coffeeService.reloadCoffee();
		orderService.reloadOrder();
	}
}

